package connpool

import (
	"encoding/binary"
	"io"
	"net"
	"time"

	"gitee.com/yutiandou/wdtools/wdlog"

	"gitee.com/yutiandou/wdRPC/server/config"
)

//CltNode ..服务器存储的客户端连接实例节点
type CltNode struct {
	ID   uint32
	Conn net.Conn
	quit chan<- uint32
}

//NewCltMsg ..创建新客户端
func NewCltNode(cid uint32, conn net.Conn, q chan<- uint32) *CltNode {
	node := &CltNode{
		ID:   cid,
		Conn: conn,
		quit: q,
	}
	node.Conn.SetDeadline(time.Now().Add(time.Second * time.Duration(config.Conf.MaxIdleTime)))
	return node
}

func (c *CltNode) Read(rout map[uint32]RoutHandler) {
	for {
		buf := make([]byte, 8)
		_, err := io.ReadFull(c.Conn, buf)
		if wdlog.Error(err) {
			c.quit <- c.ID
			break
		}
		purpose := binary.LittleEndian.Uint32(buf[:4])
		len := binary.LittleEndian.Uint32(buf[4:])
		if len > config.Conf.MaxMessageLength {
			//TODO 消息长度超限
		}
		buf = make([]byte, len)
		_, err = io.ReadFull(c.Conn, buf)
		if wdlog.Error(err) {
			c.quit <- c.ID
			break
		}
		if _, ok := rout[purpose]; ok {
			rout[purpose](c, &buf)
		}
	}
}

func (c *CltNode) WriteOld(purpose uint32, value []byte) {
	//value, err := json.Marshal(v)
	len := len(value)
	// if wdlog.Error(err) {
	// 	return
	// }
	data := make([]byte, 8)
	binary.LittleEndian.PutUint32(data, purpose)
	binary.LittleEndian.PutUint32(data[4:], uint32(len))
	data = append(data, value...)
	c.Conn.Write(data)
}

//同步机制中返回消息
func (c *CltNode) Write(value []byte) {
	purpose := uint32(100)
	//value, err := json.Marshal(v)
	len := len(value)
	// if wdlog.Error(err) {
	// 	return
	// }
	data := make([]byte, 8)
	binary.LittleEndian.PutUint32(data, purpose)
	binary.LittleEndian.PutUint32(data[4:], uint32(len))
	data = append(data, value...)
	c.Conn.Write(data)
}

func (c *CltNode) Close() {
	c.quit <- c.ID
	c.Conn.Close()
}
